﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SponsorshipManager.Interfaces;
using System.ComponentModel;
using SponsorshipManager.Client.Services;

namespace SponsorshipManager.Client.Model
{
    public delegate void CurrentUserChangedEventHandler(IUser CurrentUser);

    public class User : IUser, INotifyPropertyChanged 
    {

        private static IUser currentUser;
        public static IUser CurrentUser 
        {
            get
            {
                return currentUser;
            }
            set
            {
                currentUser = value;
                
            }
        }

        public string Username
        { get; set; }

        public int UserId
        { get; set; }
        
        public int PersonId
        { get; set; }
        
        public int OrgId
        { get; set; }

        public int UserLevel
        {get; set;}

        public string Token
        { get; set; }

        public DateTime Timestamp
        {
            get;
            set;
        }

        public static event  CurrentUserChangedEventHandler ChangedCurrentUser;
        public event PropertyChangedEventHandler PropertyChanged;

        internal static bool LoginUser(string Username, string Password)
        {
            var us = new SponsorshipManager.Client.Services.ServicesClient();
            UserData AuthenticatedUser = us.Authenticate(Username, Password);
            if (AuthenticatedUser != null)
            {
                CurrentUser = new User();
                CurrentUser.PersonId = AuthenticatedUser.PersonId;
                CurrentUser.Timestamp = AuthenticatedUser.Timestamp;
                CurrentUser.Token = AuthenticatedUser.Token;
                CurrentUser.UserId = AuthenticatedUser.UserId;
                CurrentUser.UserLevel = AuthenticatedUser.UserLevel;
                CurrentUser.Username = AuthenticatedUser.Username;

                ChangedCurrentUser(CurrentUser);
                return true;
            }
            else
                return false;
            
            //throw new NotImplementedException();
        }

        private IPerson _person; 
        public IPerson Person
        {
            get
            {
                if (_person == null) _person = Model.Person.Load(PersonId);
                return _person; 
            }
        }
       
    }
}
